package cn.pa4j.utils;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.setting.Setting;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;

/**
 * @author 060016
 */
public class WxUtil {

    public static Setting setting = new Setting("wx.setting");

    /**
     * 校验微信token
     *
     * @param req HttpServletRequest
     * @param token token
     * @return checkIsWx
     */
    public static boolean checkIsWx(HttpServletRequest req, String token) {
        String signature = req.getParameter("signature");
        if (signature != null) {
            String timestamp = req.getParameter("timestamp");
            String nonce = req.getParameter("nonce");
            String[] parms = new String[]{token, timestamp, nonce};
            Arrays.sort(parms);
            String parmsString = "";
            for (String parm : parms) {
                parmsString += parm;
            }
            String mParms = new Digester(DigestAlgorithm.SHA1).digestHex(parmsString);
            return mParms.equals(signature);
        } else {
            return false;
        }
    }

    /**
     * 获取access_token并存储到本地文件中，超过两个小时则重新获取
     *
     * @return access_token
     */
    public static String getAccessToken() {
        File file = FileUtil.file("access_token.txt");
        JSONObject jsonObject;
        String s = "";
        if (file.exists()) {
            s = FileUtil.readUtf8String(file);
        }
        if (!"".equals(s) && DateUtil.between(DateUtil.date(new JSONObject(s).getLong("time")), DateUtil.date(), DateUnit.HOUR) < 2) {
            return new JSONObject(s).getStr("access_token");
        } else {
            jsonObject = new JSONObject();
            String appid = setting.getStr("appid");
            String secert = setting.getStr("secret");
            String post = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secert, (String) null);
            String token = new JSONObject(post).getStr("access_token");
            jsonObject.put("access_token", token);
            jsonObject.put("time", DateUtil.current(false));
            FileUtil.writeUtf8String(JSONUtil.toJsonStr(jsonObject), file);
            FileUtil.touch(file);
            return token;
        }
    }

    /**
     * 发送模板消息，template_id要是自己的模板ID
     * templetText中为根据模板写的jsonStr
     *
     * @param touser 收信人
     * @param title 标题
     * @param content 内容
     * @return result
     */
    public static String sendWithTemplet(String roomID,String touser, String content, String title) {
        String templetText = "{" +
                "     \"touser\":\"" + touser + "\", " +
                "     \"url\":\"" + "https://live.bilibili.com/"+roomID + "\", " +
                "     \"template_id\":\"7en_3So7C1RnWbHujX3CpoY2fXataApxoDQ6xxifR80\", " +
                "     \"data\":{ " +
                "             \"title\": { " +
                "                 \"value\":\"" + title + "\"" +
                "             }, " +
                "             \"first\": { " +
                "                 \"value\":\"" + content + "\"" +
                "             }" +
                "     } " +
                " }  ";
        String accessToken = WxUtil.getAccessToken();
        return HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken, templetText);
    }
}
